package com.ymttest.database.sharding.config;

import java.util.Properties;

import javax.sql.DataSource;

import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.support.TransactionTemplate;

import com.alibaba.druid.pool.DruidDataSource;

public class DbExtSourceConfig {

	private ConnectionConfig connectionConfig = ConnectionConfig.getInstance();

	private static DbExtSourceConfig dbExtSourceConfig = null;

	private DbExtSourceConfig() {
	}

	public DataSource extDataSource() {

		DruidDataSource dataSource = DataSourceUtils.initDataSource();
		
		dataSource.setUrl(connectionConfig.getExtDbUrl());
		dataSource.setUsername(connectionConfig.getExtDbUser());
		dataSource.setPassword(connectionConfig.getExtDbPassword());
		dataSource.setDefaultAutoCommit(true);
		return dataSource;
	}

	public SqlSessionFactory extSessionFactory() throws Exception {

		SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();

		// 获取properties中的对应配置信息
		String mapperLocation = "classpath*:com/ymttest/database/sharding/sqlmap/ext/**/*.xml";

		//String configLocation = "classpath:mybatis-settings.xml";

		Properties properties = new Properties();

		sessionFactory.setDataSource(extDataSource());
		sessionFactory.setConfigurationProperties(properties);

		// 设置MapperLocations configLocation路径
		ResourcePatternResolver resourcePatternResolver = new PathMatchingResourcePatternResolver();
		sessionFactory.setMapperLocations(resourcePatternResolver
				.getResources(mapperLocation));

		/*		sessionFactory.setConfigLocation(resourcePatternResolver
						.getResource(configLocation));*/

		return sessionFactory.getObject();
	}

	public SqlSessionTemplate extSessionTemplate() throws Exception {
		return new SqlSessionTemplate(extSessionFactory());
	}

	public PlatformTransactionManager extTransactionManager() {
		return new DataSourceTransactionManager(extDataSource());
	}

	public TransactionTemplate extTransactionTemplate() {
		return new TransactionTemplate(extTransactionManager());
	}

	public static DbExtSourceConfig getInstance() {

		if (dbExtSourceConfig == null) {

			dbExtSourceConfig = new DbExtSourceConfig();

		}

		return dbExtSourceConfig;
	}
}
